<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

// 课程章节
class Chapter extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Subject.Chapter');
    }

    // 查看
    public function index()
    {

        if ($this->request->isAjax())
        {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    //添加
    public function add($ids = null)
    {
        if ($this->request->isPost())
        {
            // 获取表单数据
            $params = $this->request->post('row/a');

            $params['subid'] = $ids;

            $result = $this->model->validate('common/Subject/Chapter')->save($params);

            if ($result === false)
            {
                $this->error($this->model->getError());
                exit;
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row)
        {
            $this->error(__('课程章节不存在'));
        }

        if ($this->request->isPost())
        {
            // 获取表单数据
            $params = $this->request->post('row/a');
            $params['id'] = $ids;

            $result = $this->model->validate('common/Subject/Chapter.edit')->isUpdate(true)->save($params);

            if ($result === false)
            {
                $this->error($this->model->getError());
                exit;
            }

            //判断是否有上传新视频
            if ($row['url'] != $params['url'])
            {
                //不相等就说明有换视频了，就删除掉旧视频
                @is_file("." . $row['url']) && @unlink("." . $row['url']);
            }

            $this->success();
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    // 删除
    public function del($ids = null)
    {
        $row = $this->model->select($ids);

        if (!$row)
        {
            $this->error(__('课程章节不存在'));
        }

        $result = $this->model->destroy($ids);

        if ($result === false)
        {
            $this->error($this->model->getError());
            exit;
        }

        foreach($row as $item)
        {
             //不相等就说明有换图片了，就删除掉旧图片
             @is_file("." . $item['url']) && @unlink("." . $item['url']);
        }

        $this->success();
    }
}